package main

import (
	"fmt"
	"net/http"
	"strings"
	"log"
	"text/template"
	"strconv"
	"time"
	"crypto/md5"
	"io"
	"os"
)

func sayhellName(w http.ResponseWriter, r *http.Request){
	r.ParseForm()	//解析参数，默认是不会解析的

	fmt.Println("path", r.Form)		//这些信息是输出到服务器的打印信息
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])

	for k,v := range r.Form{
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v,""))
	}

	fmt.Fprintf(w, "Hello astaxie!" + strings.Join(r.Form["url_long"],""))
}

func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		t, _ := template.ParseFiles("login.gtpl")
		log.Println(t.Execute(w, nil))
	} else {
		//请求的是登陆数据，那么执行登陆的逻辑判断
		r.ParseForm()
		fmt.Println("username:", r.Form["username"])
		fmt.Println("password:", r.Form["password"])

		if r.FormValue("username") == "" {
			fmt.Fprintf(w, "用户名不能为空")
			return
		}

		if len(r.Form["username"][0]) != 3 {
			fmt.Fprintf(w, "用户名为3位数字")
			return
		}

		_,err := strconv.Atoi(r.Form.Get("username"))
		if err != nil {
			//数字转化出错了，包含非数字
			fmt.Fprintf(w, "用户名只能是纯数字")
			return
		}
		fmt.Fprintf(w, "Hello astaxie!")

		fmt.Fprintf(w,  r.Form.Get("fruit"))
	}
}

func upload(w http.ResponseWriter, r *http.Request){
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)  // 此处假设当前目录下已存在test目录
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}
}

func main()  {
	http.HandleFunc("/", sayhellName)	//设置反问的路由
	http.HandleFunc("/login", login)	//设置反问的路由
	http.HandleFunc("/upload", upload)	//设置反问的路由

	err := http.ListenAndServe(":9090",nil)
	if err != nil{
		log.Fatal("ListenAndServe:",err)
	}
}